import React from 'react';
import { render } from 'react-dom';
import { Form, Icon, Input, Button, Checkbox, Upload, Modal } from 'antd';

class NormalRegisterForm extends React.Component {
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                try {
                    document.getElementById('avatar').value = this.state.fileList[0].response.url;
                } catch (e) { }
                document.getElementById('main-form').submit();
            }
        });
    };

    state = {
        confirmDirty: false,
        autoCompleteResult: [],
    };

    handleConfirmBlur = e => {
        const { value } = e.target;
        this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    };

    compareToFirstPassword = (rule, value, callback) => {
        const { form } = this.props;
        if (value && value !== form.getFieldValue('password')) {
            callback('Two passwords that you enter is inconsistent!');
        } else {
            callback();
        }
    };

    validateToNextPassword = (rule, value, callback) => {
        const { form } = this.props;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], { force: true });
        }
        callback();
    };

    getBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }


    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = file => {
        if (!file.url && !file.preview) {
            this.getBase64(file.originFileObj).then(data => {
                file.preview = data;
                this.setState({
                    previewImage: file.url || file.preview,
                    previewVisible: true,
                });
            });
        }
        else {
            this.setState({
                previewImage: file.url || file.preview,
                previewVisible: true,
            });
        }
    };

    handleChange = ({ fileList }) => {
        this.setState({ fileList })
    };

    state = {
        previewVisible: false,
        previewImage: '',
        fileList: []
            // {
            //     uid: '-1',
            //     name: 'image.png',
            //     status: 'done',
            //     url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
            // }]
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload avatar</div>
            </div>
        );

        return (
            <div>
                <Form id="main-form" onSubmit={this.handleSubmit} className="main-form" action="/register" method="post">
                    <Form.Item>
                        {getFieldDecorator('email', {
                            rules: [
                                {
                                    type: 'email',
                                    message: 'The input is not valid E-mail!',
                                },
                                {
                                    required: true,
                                    message: 'Please input your E-mail!',
                                },
                            ],
                        })(<Input name="email"
                            prefix={<Icon type="mail" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="E-mail!" />)}
                    </Form.Item>
                    <Form.Item>
                        {getFieldDecorator('username', {
                            rules: [{ required: true, message: 'Please input your username!' }],
                        })(
                            <Input name="user"
                                prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="Username"
                            />,
                        )}
                    </Form.Item>
                    <Form.Item hasFeedback>
                        {getFieldDecorator('password', {
                            rules: [{ required: true, message: 'Please input your Password!' },
                            {
                                validator: this.validateToNextPassword,
                            },],
                        })(
                            <Input.Password name="pass"
                                prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                type="password"
                                placeholder="Password" onBlur={this.handleConfirmBlur}
                            />,
                        )}
                    </Form.Item>
                    <Form.Item hasFeedback>
                        {getFieldDecorator('confirm', {
                            rules: [
                                {
                                    required: true,
                                    message: 'Please confirm your password!',
                                },
                                {
                                    validator: this.compareToFirstPassword,
                                },
                            ],
                        })(<Input.Password onBlur={this.handleConfirmBlur}
                            prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            type="password"
                            placeholder="Confirm Password" />)}
                    </Form.Item>
                    <Upload
                        accept="image/*"
                        action="/file/upload"
                        listType="picture-card"
                        data = {{fileType: 'avatars'}}
                        fileList={fileList}
                        onPreview={this.handlePreview}
                        onChange={this.handleChange}
                    >
                        {fileList.length >= 1 ? null : uploadButton}
                    </Upload>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" className="main-form-button">Create</Button>
                        Or <a href="login">login now!</a>
                    </Form.Item>
                    <input type="hidden" id="avatar" name="avatar"></input>
                </Form>

                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}

const WrappedNormalLoginForm = Form.create({ name: 'normal_login' })(NormalRegisterForm);

render(<WrappedNormalLoginForm />, document.getElementById('main-container'));